package com.leenmvc.core.security;


import com.alibaba.fastjson.JSONObject;
import com.leenmvc.core.dao.communal.TransactionManager;
import com.leenmvc.core.dao.communal.Wrapper;
import com.leenmvc.core.exception.BusinessException;
import com.leenmvc.core.security.entity.core.SysUser;
import com.leenmvc.core.utils.thread.ThreadLocalManager;
import com.leenmvc.core.base.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * oauth2过滤器
 *
 * @author leen
 */
public class Oauth2Filter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        // 获取请求token
        String token = getRequestToken((HttpServletRequest) request);

        if(StringUtils.isBlank(token)){
            return null;
        }
        return new Oauth2Token(token);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        String token = getRequestToken((HttpServletRequest) request);
        if(StringUtils.isBlank(token)){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setContentType("application/json;charset=utf-8");
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            Result error = new Result().unauthorized("无效请求， 请传递有效的token!");
            error.setCode(402);
            String result = JSONObject.toJSONString(error);
            httpResponse.getWriter().print(result);
            return false;
        }
        return executeLogin(request, response);
    }

    /**
     * 登录失败
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
//        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
        try {
            // 处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            String result = null;
            if(e.getCause() instanceof BusinessException) {
                Result error = new Result().info(e.getCause().getMessage());
                error.setCode(402);
                result = JSONObject.toJSONString(error);
            } else {
                Result error = new Result().unauthorized("请传递有效的token!");
                error.setCode(402);
                result = JSONObject.toJSONString(error);
            }
            httpResponse.getWriter().print(result);
        } catch (IOException e1) {

        }
        return false;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        if(!TransactionManager.transExist()) {
            TransactionManager.setTrans(0); // 本线程事务初始状态默认为不开启
            ThreadLocalManager.setWrapperList(new ArrayList<Wrapper>());
            ThreadLocalManager.setGlobalVariable(new HashMap<String, Object>());
            ThreadLocalManager.setIsLog(0);
            ThreadLocalManager.setUser(new SysUser());
            ThreadLocalManager.setRequestTime(System.currentTimeMillis());
            ThreadLocalManager.setRequest(httpRequest);
        }
        // 从header中获取token
        String token = httpRequest.getHeader("token");

        // 如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("token");
        }

        return token;
    }

}
